using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Tools.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DataSplitController : ControllerBase
    {
        private readonly ILogger<DataSplitController> _logger;

        public DataSplitController(ILogger<DataSplitController> logger)
        {
            _logger = logger;
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        }

        [HttpPost("split")]
        public async Task<IActionResult> SplitData([FromForm] IFormFile file, [FromForm] int splitCount = 500)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { success = false, message = "请选择要拆分的文件" });
                }

                if (splitCount <= 0)
                {
                    return BadRequest(new { success = false, message = "拆分条数必须大于0" });
                }

                // 验证文件类型
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    return BadRequest(new { success = false, message = "仅支持.xlsx和.xls格式的Excel文件" });
                }

                // 处理Excel文件拆分
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    stream.Position = 0;

                    using (var package = new ExcelPackage(stream))
                    {
                        var result = SplitExcelFile(package, splitCount, file.FileName);
                        return File(result.FileContent, "application/zip", result.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据拆分失败");
                return StatusCode(500, new { success = false, message = $"数据拆分失败: {ex.Message}" });
            }
        }

        private (byte[] FileContent, string FileName) SplitExcelFile(ExcelPackage package, int splitCount, string originalFileName)
        {
            var splitFiles = new List<byte[]>();
            var worksheet = package.Workbook.Worksheets[0];
            var dimension = worksheet.Dimension;
            if (dimension == null)
            {
                throw new InvalidOperationException("工作表没有数据");
            }
            var totalRows = dimension.Rows;
            var headerRow = 1; // 假设第一行是表头
            var dataRows = totalRows - headerRow;
            var totalSheets = (int)Math.Ceiling((double)dataRows / splitCount);

            // 创建一个新的Excel包用于存储拆分后的文件
            using (var zipStream = new MemoryStream())
            using (var archive = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode.Create, true))
            {
                for (int i = 0; i < totalSheets; i++)
                {
                    var startRow = headerRow + i * splitCount + 1;
                    var endRow = Math.Min(headerRow + (i + 1) * splitCount, totalRows);
                    var rowsToCopy = endRow - startRow + 1;

                    // 创建新的Excel包
                    using (var newPackage = new ExcelPackage())
                    {
                        var newWorksheet = newPackage.Workbook.Worksheets.Add($"拆分文件_{i + 1}");

                        // 复制表头
                        worksheet.Cells[headerRow, 1, headerRow, dimension.Columns].Copy(newWorksheet.Cells[headerRow, 1]);

                        // 复制数据行
                        if (startRow <= endRow)
                        {
                            worksheet.Cells[startRow, 1, endRow, dimension.Columns].Copy(newWorksheet.Cells[headerRow + 1, 1]);
                        }

                        // 保存到内存流
                        var fileBytes = newPackage.GetAsByteArray();
                        var entryName = $"{Path.GetFileNameWithoutExtension(originalFileName)}_拆分_{i + 1}.xlsx";
                        var entry = archive.CreateEntry(entryName);

                        using (var entryStream = entry.Open())
                        {
                            entryStream.Write(fileBytes, 0, fileBytes.Length);
                        }
                    }
                }

                // 准备返回结果
                zipStream.Position = 0;
                var zipBytes = zipStream.ToArray();
                var zipFileName = $"{Path.GetFileNameWithoutExtension(originalFileName)}_拆分结果_{DateTime.Now:yyyyMMddHHmmss}.zip";

                return (zipBytes, zipFileName);
            }
        }
    }
}